import 'dart:collection';
import 'dart:io';

import 'package:dio/dio.dart';
import 'package:gsy_flutter_app/common/config/Config.dart';
import 'package:gsy_flutter_app/common/local/LocalStorage.dart';
import 'package:gsy_flutter_app/common/net/Code.dart';
import 'package:gsy_flutter_app/common/net/ResultData.dart';

/// 作者: Tao
/// 日期: 2024/1/17
/// 时间: 14:09
/// 描述: Http请求管理类
class HttpManager {
  static const CONTENT_TYPE_JSON = "application/json";
  static const CONTENT_TYPE_FORM = "application/x-www-form-urlencoded";
  static Map optionParams = {
    "timeoutMs": 15000,
    "token": null,
    "authorizationCode": null,
  };

  ///发起网络请求
  ///[url] -请求url
  ///[params] 请求参数
  ///[header] 外加头
  ///[text] 是否text返回
  ///[option] 配置
  ///return: [ResultData] 包装后的返回实体
  static netFetch(
      url, params, Map<String, String>? header, Options? option) async {
    Map<String, String> headers = HashMap();
    if (header != null) {
      headers.addAll(header);
    }

    //授权码
    if (optionParams["authorizationCode"] == null) {
      var authorizationCode = await getAuthorization();
      if (authorizationCode != null) {
        optionParams["authorizationCode"] = authorizationCode;
      }
    }

    headers["Authorization"] = optionParams["authorizationCode"];

    if (option != null) {
      option.headers = headers;
    } else {
      option = Options(method: "get");
      option.headers = headers;
    }
    option.headers = headers;

    print("请求url: $url");

    Dio dio = Dio();
    Response response;
    try {
      response = await dio.request(url, data: params, options: option);
    } on DioException catch (e) {
      Response errorResponse;
      if (e.response != null) {
        errorResponse = e.response!;
      } else {
        errorResponse =
            Response(requestOptions: RequestOptions(), statusCode: 666);
      }
      if (e.type == DioExceptionType.connectionTimeout) {
        errorResponse.statusCode = Code.NETWORK_TIMEOUT;
      }
      if (Config.DEBUG) {
        print('请求异常: ' + e.toString());
      }
      return ResultData(
          Code.errorHandleFunction(errorResponse.statusCode, e.message),
          false,
          errorResponse.statusCode);
    }
    if (Config.DEBUG) {
      if (Config.DEBUG) {
        print("请求url: $url");
        if (params != null) {
          print('请求参数: $params');
        }
        print('返回参数: $response');
      }
    }

    try {
      if (option.contentType != null && option.contentType == "text") {
        return ResultData(response.data, true, Code.SUCCESS);
      } else {
        var responseJson = response.data;
        if (response.statusCode == 201 && responseJson["token"] != null) {
          optionParams["authorizationCode"] = 'token ${responseJson["token"]}';
          await LocalStorage.save(
              Config.TOKEN_KEY, optionParams["authorizationCode"]);
        }
      }

      if (response.statusCode == 200 || response.statusCode == 201) {
        return ResultData(response.data, true, Code.SUCCESS,
            headers: response.headers);
      }
    } catch (e) {
      print(e.toString() + url);
      return ResultData(response.data, false, response.statusCode,
          headers: response.headers);
    }
    return ResultData(Code.errorHandleFunction(response.statusCode, ""), false,
        response.statusCode);
  }

  /// 方法描述: 清除授权的token
  static clearAuthorization() {
    optionParams["authorizationCode"] = null;
    LocalStorage.remove(Config.TOKEN_KEY);
  }

  /// 方法描述: 获取认证Token
  /// return: [token] - 认证token
  static getAuthorization() async {
    var token = await LocalStorage.get(Config.TOKEN_KEY);
    if (token == null) {
      var basic = LocalStorage.get(Config.USER_BASIC_CODE);
      if (basic == null) {
        //提示输入账号密码
      } else {
        //通过 basic 去获取token，获取到设置，返回token
        return "Basic$basic";
      }
    } else {
      return token;
    }
  }
}
